package com.tjsoft.demo.student.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.tjsoft.demo.student.model.CartModel;
import com.tjsoft.demo.student.model.OrderListModel;
import com.tjsoft.demo.student.model.ProductModel;
import com.tjsoft.demo.student.model.PurchaseGoodModel;
import com.tjsoft.demo.student.model.UserModel;
import com.tjsoft.demo.student.service.FreshCutService;
import com.tjsoft.demo.util.HibernateEntityDao;
import com.tjsoft.demo.webChat.util.IDFactory;

public  class FreshCutServiceImpl implements FreshCutService {
	public HibernateEntityDao<ProductModel> freshServerDAO;
	public HibernateEntityDao<CartModel> cartModelDAO;
	public HibernateEntityDao<PurchaseGoodModel> purchaseGoodModelDAO;
	public HibernateEntityDao<OrderListModel> orderListModelDAO;
	public HibernateEntityDao<UserModel> userModelDAO;
	public HibernateEntityDao<ProductModel> getFreshServerDAO() {
		return freshServerDAO;
	}
	public void setFreshServerDAO(HibernateEntityDao<ProductModel> freshServerDAO) {
		this.freshServerDAO = freshServerDAO;
	}
	@Override
	public String findListFreshCut(int sort) {
		// TODO Auto-generated method stub
		String hql="from ProductModel t where 1=1 and t.sort=?";
		System.out.println("查找商品列表:"+hql);
		Object[] o=new Object[1];
		o[0]=sort;
		JSONObject obj=new JSONObject();
		JSONObject al=new JSONObject();
		JSONArray recommond=new JSONArray();
		JSONArray special=new JSONArray();
		JSONArray common=new JSONArray();
		try{
		List<ProductModel> allProudct=freshServerDAO.findList(hql, o);
		for(ProductModel product: allProudct){
			  if(product.getSpecialProduct()==0){//推荐产品
				  obj=JSONObject.fromObject(product);
				  recommond.add(obj);				  
			  }else if(product.getSpecialProduct()==1){//特别商品
				  obj=JSONObject.fromObject(product);
				  special.add(obj);
				  
			  }else {//普通商品
				  obj=JSONObject.fromObject(product);
				  common.add(obj);
			  }			 
		}
		al.put("recommend", recommond);
		al.put("special", special);
		al.put("common", common);
		}catch(Exception e){
			System.out.println(e+"findListFrshCut.查找商品列表发生异常");
			e.printStackTrace();
		}
		System.out.println(al.toString());
		return al.toString();
	}
	@Override
	public String showProductDetail(int productId) {
		// TODO Auto-generated method stub	  
	    System.out.println("查找商品列表:");
		Object[] o=new Object[1];
		JSONObject detail=new JSONObject();
		o[0]=productId;
		try{
			ProductModel productDetail=freshServerDAO.findUnique("productId", productId);
			detail=JSONObject.fromObject(productDetail);	
		}catch(Exception e){
			System.out.println("查找商品详情发生异常"+e);
			e.printStackTrace();
		}
		return detail.toString();
	}
	@Override
	public String browserCart(String  id,String[] purchse) {
		// TODO Auto-generated method stub
		
		return null;
	}

	 public String addToCart(String userId,String cartID,String[] productId,String[] counts){
		// TODO Auto-generated method stub
		  //购物车，查看是有该用户的购物车，并且是未结账的，如果有，则在原来的基础上修改，如果没有则新建一个
 //        CartModel cart=new CartModel();
  //       String findCart="from cartModel where 1=1 and userId=?";
//		 if()修改购物车的时候在判断了
         JSONObject obj1=new JSONObject();//外层
         JSONObject obj2=new JSONObject();//选购商品
         JSONArray arr=new JSONArray();//选购商品列表    
         Double totalMoney=0.0;
		 CartModel cart=new CartModel();
		 try{    
				 if(!cartID.isEmpty()&&!cartID.equals("0")){//删除购物车，重新添加
					 cart=cartModelDAO.findUnique("cartId", cartID);
					 if(cart!=null){
					      cartModelDAO.remove(cart);
					 }
					 PurchaseGoodModel purchase=new PurchaseGoodModel();
					 String hql="delete PurchaseGoodModel where 1=1 and cartId=?";
					 if(purchaseGoodModelDAO.findBy("cartId", cartID).size()>0){
						 	purchaseGoodModelDAO.remove(hql, new Object[]{cartID});
					 }
				 }
			  String cartId=IDFactory.getId();//购物车ID
         	  for(int i=0;i<counts.length;i++){
        		 ProductModel product=(ProductModel) freshServerDAO.findUnique("productId", productId[i]);
        		 Double pro=Integer.valueOf(counts[i])*product.getPricePri();
        		 totalMoney+=pro;
            	 PurchaseGoodModel purchase=new PurchaseGoodModel();//写入到数选购表中
            	 purchase.setCartId(cartId);//购物车id
            	 purchase.setCount(Integer.valueOf(counts[i]));//商品数量
            	 purchase.setPrice(product.getPricePri());
            	 purchase.setProductId(productId[i]);//商品ID
            	 System.out.println(IDFactory.getId()+"--------------");
            	 purchase.setPurchasedId(Long.valueOf(IDFactory.getId()));//选购记录ID
            	 purchase.setOther("");
            	 purchase.setTotalPrice(Integer.valueOf(counts[i])*product.getPricePri());//总价
            	 purchaseGoodModelDAO.save(purchase);
            	 purchaseGoodModelDAO.getHibernateTemplate().flush();
            	 obj1.put("productId", productId[i]);
            	 obj1.put("productName", product.getProductName());
            	 obj1.put("price", product.getPricePri());
            	 obj1.put("count", counts[i]);
            	 System.out.println("---"+product.getStandard());
            	 obj1.put("standard", product.getStandard());
            	 obj1.put("productImage", product.getProductImage());
            	 arr.add(obj1);
         	  }
         	  obj2.put("cart", arr);
         	  obj2.put("totalMoney",totalMoney);
         	  obj2.put("cartId", cartId);
         //写入到购物车中
         cart.setCartId(Long.valueOf(cartId));
         cart.setStatus(0);//0未完结 1已结款
         cart.setTotalMoney(totalMoney);
         cart.setUserId(userId);
         cartModelDAO.save(cart);
         cartModelDAO.getHibernateTemplate().flush();
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		return obj2.toString();
	}
	@Override
	public String viewCart(int cartId) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String delCartSelectProudct(int cartId, int productId) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String updateSelected() {
		// TODO Auto-generated method stub
		return null;
	}
	public HibernateEntityDao<CartModel> getCartModelDAO() {
		return cartModelDAO;
	}
	public void setCartModelDAO(HibernateEntityDao<CartModel> cartModelDAO) {
		this.cartModelDAO = cartModelDAO;
	}
	public HibernateEntityDao<PurchaseGoodModel> getPurchaseGoodModelDAO() {
		return purchaseGoodModelDAO;
	}
	public void setPurchaseGoodModelDAO(
			HibernateEntityDao<PurchaseGoodModel> purchaseGoodModelDAO) {
		this.purchaseGoodModelDAO = purchaseGoodModelDAO;
	}
	public HibernateEntityDao<OrderListModel> getOrderListModelDAO() {
		return orderListModelDAO;
	}
	public void setOrderListModelDAO(
			HibernateEntityDao<OrderListModel> orderListModelDAO) {
		this.orderListModelDAO = orderListModelDAO;
	}
	public HibernateEntityDao<UserModel> getUserModelDAO() {
		return userModelDAO;
	}
	public void setUserModelDAO(HibernateEntityDao<UserModel> userModelDAO) {
		this.userModelDAO = userModelDAO;
	}
	@Override
	public String clearCart() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String registUser(String PhoneNum, String Address, String Name) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String submitOrder(String userId, String cartID, String[] productId, String[] counts) {			
		// TODO Auto-generated method stub
		//提交的订单，只是修改购物车中商品的数量和购物车的状态，然后原样返回
        JSONObject obj1=new JSONObject();//外层
        JSONObject obj2=new JSONObject();//选购商品
        JSONArray arr=new JSONArray();//选购商品列表    
        JSONArray order=new JSONArray();//用户信息
        JSONObject userObj=new JSONObject();//存用户信息
        JSONObject orderObj=new JSONObject();
        Double totalMoney=0.0;
		CartModel cart=new CartModel();
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  	   Date date=new Date();      
		 try{    
				 if(!cartID.isEmpty()&&!cartID.equals("0")){//删除购物车，重新添加
					 cart=cartModelDAO.findUnique("cartId", Long.valueOf(cartID));
					 if(cart!=null){
					      cartModelDAO.remove(cart);
					      cartModelDAO.getHibernateTemplate().flush();
					 }
					 PurchaseGoodModel purchase=new PurchaseGoodModel();
					 String hql="delete PurchaseGoodModel where 1=1 and cartId=?";
					 if(purchaseGoodModelDAO.findBy("cartId",  Long.valueOf(cartID)).size()>0){//删除所有选购商品
						 purchaseGoodModelDAO.executeSQL(hql, new Object[]{Long.valueOf(cartID)});
					 }
				 }
	 		 Long OrderId= Long.valueOf(IDFactory.getId());//购物车ID
        	 for(int i=0;i<counts.length;i++){
             //获取指定商品
       		 ProductModel product=(ProductModel) freshServerDAO.findUnique("productId", productId[i]);
       		 Double unitPrice=Integer.valueOf(counts[i])*product.getPricePri();
       		 totalMoney+=unitPrice;
           	 PurchaseGoodModel purchase=new PurchaseGoodModel();//写入到数选购表中
           	 //更新数量到选购表中
           	 String updatePurchase="update PurchaseGoodModel m set m.count=? where 1=1 and cartId=?";
           	 Object update =purchaseGoodModelDAO.update(updatePurchase, new Object[]{Integer.valueOf(counts[i]), Long.valueOf(cartID)});
             //作为输出
           	// obj1.put("productId", productId[i]);
           	 obj1.put("unitPrice",unitPrice);
           	 obj1.put("productName", product.getProductName());
           	 obj1.put("price", product.getPricePri());
           	 obj1.put("count", counts[i]);
           	 System.out.println("---"+product.getStandard());
           	 obj1.put("standard", product.getStandard());
           	// obj1.put("productImage", product.getProductImage());
           	 arr.add(obj1);
        	 }
             //生成订单
        	  OrderListModel orderlist=new OrderListModel();
        	  orderlist.setCartId(Long.valueOf(cartID));
        	  orderlist.setOrderDate(date);
        	  orderlist.setOrderNumber(11);
        	  orderlist.setOrderStutes(0);
        	  orderListModelDAO.save(orderlist);
        	  orderListModelDAO.getHibernateTemplate().flush();
        	  
        	  //拼接后天返回数据
        	  obj2.put("orderDate",format.format(date).toString());
        	  obj2.put("purchasedgood", arr);
        	  obj2.put("totalMoney",totalMoney.toString());
        	  obj2.put("orderNumber",OrderId);
        	  obj2.put("orderStutes",0 );
        	  obj2.put("msg", "下单成功");
        	  UserModel user=new UserModel();
        	  user=userModelDAO.findUnique("userId",Long.valueOf(userId));
        	  userObj.put("name",user.getName() );
        	  userObj.put("address", user.getAddress());
        	  userObj.put("phoneNumber", user.getPhoneNumber());
        	  orderObj.put("order", obj2);
        	  orderObj.put("user", orderObj);
        	  
              //写入到购物车中 
        	  String updateCart="update CartModel c set c.status=?,c.totalMoney=? where 1=1 and cartId=?";
        	  cartModelDAO.update(updateCart, new Object[]{1,totalMoney,cartID});//1购物车已经完结
              cartModelDAO.getHibernateTemplate().flush();
              
    
              
		 }catch(Exception e){
			 System.out.println(e+"用户"+userId);
			 e.printStackTrace();
			 return "{'order': {'orderStutes': -1, 'msg': '下单失败，没有此商品' }}";
			 
		 }
		return "{"+orderObj.toString()+"}";
	}
	
	/**
	 * 查看历史订单，还是只查询当为结算完成
	 */
	@Override
	public  String checkOrder(String userId,String orderstatus){
		JSONObject order=new JSONObject();
		JSONObject listorder=new JSONObject();
		JSONObject products=new JSONObject();
		JSONObject user=new JSONObject();
		JSONObject objHis=new JSONObject();
		JSONArray  arrOrders=new JSONArray();
		JSONArray arr=new JSONArray();
		int i=1;
	   try{
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //获取购物车信息
		 //查找购物车
        String findCart="from cartModel order by cartId desc where  userId=? and  status= ? rownum<=?";
         //from TCase as tCase order by case when tCase.handleResult = '已处理' then '1' end
         //查找最新前10个购物车
        List<CartModel> cartmodel=cartModelDAO.findBy(findCart,new Object[]{userId ,1,10});
        for(CartModel cartDo:cartmodel){//根据购物车查找ID
        	    Long cartId=cartDo.getCartId();
        	 if(Integer.valueOf(orderstatus)<3&&Integer.valueOf(orderstatus)>-1){//表示查看查看的是订单为未完结
        		   ///获取指定订单及其购买的商品
        		    String hql="from OrderListModel c where c.cartId=? and c.status<=? and c.status>?";
        		    OrderListModel orderList=(OrderListModel) orderListModelDAO.createQuery(hql, new Object[]{cartId,-1,3});//为完成的订单
        		    order.put("orderId", orderList.getOrderId());
        			order.put("orderDate",format.format(orderList.getOrderDate()));
        		    order.put("orderStatus", orderList.getOrderStutes());
        		    //获取选购过的商品
        		    List<PurchaseGoodModel> list=purchaseGoodModelDAO.findBy("cartId",cartId);
        			   for(PurchaseGoodModel purchase:list){
        				   ProductModel product=(ProductModel) freshServerDAO.findUnique("productId", purchase.getProductId());
        				   products.put("productName", product.getProductName());
        				   products.put("count",purchase.getCount());
        				   products.put("standard",product.getStandard() );
        				   products.put("totalPrice", purchase.getTotalPrice().toString());
        				   arr.add(products);
        			   }
        			   order.put("purchasedgood", arr);
        			   listorder.put("order"+i++, order);
      	      }else{//查询的是所有的订单，现阶段只支持查询最近的10个订单      	    	  
      		    String hql="from OrderListModel c where c.cartId=?";
      		    OrderListModel orderList=(OrderListModel) orderListModelDAO.createQuery(hql, new Object[]{cartId});//为完成的订单
      		    order.put("orderId", orderList.getOrderId());
      			order.put("orderDate",format.format(orderList.getOrderDate()));
      		    order.put("orderStatus", orderList.getOrderStutes());
      		    //获取选购过的商品
      		    List<PurchaseGoodModel> list=purchaseGoodModelDAO.findBy("cartId",cartId);
      			   for(PurchaseGoodModel purchase:list){
      				   ProductModel product=(ProductModel) freshServerDAO.findUnique("productId", purchase.getProductId());
      				   products.put("productName", product.getProductName());
      				   products.put("count",purchase.getCount());
      				   products.put("standard",product.getStandard() );
      				   products.put("totalPrice", purchase.getTotalPrice().toString());
      				   arr.add(products);
      			   }
      			   order.put("purchasedgood", arr);
      			   listorder.put("order"+i++, order);
      	    	  
      	      }
        	 arrOrders.add(listorder);        	 
         }
		objHis.put("orderHistory",arrOrders);
	   }catch(Exception e){
		  System.out.println("userId"+userId+"查询历史订单异常"+e);
	   }
	   return  "{"+objHis.toString()+"}";
   }
}
